package logic

import (
	"one-wiki/commons"
	"one-wiki/database"
	"strconv"
	"strings"
	"time"
)

func CatalogAll(session commons.Session) []*commons.CatalogResponse {

	// 用户所在组
	groups := session.Groups

	// 用户id
	id := session.UserID

	// 查询所有组拥有权限的文档资源id
	ids1 := database.ListResourceIdByGroupIds(groups, commons.RESOURCE_DOCUMENT)

	// 查询用户拥有权限的文档资源id
	ids2 := database.ListResourceIdByUserId(id, commons.RESOURCE_DOCUMENT)

	// 合并id列表
	mergedIDs := append(ids1, ids2...)

	// 查询所有文档的上级文档
	ancestorsList := database.ListAncestorsByIds(mergedIDs)

	// 合并id列表
	for _, ancestors := range ancestorsList {
		ancestorsStr := strings.Split(ancestors, ",")
		for _, ancestorStr := range ancestorsStr {
			if ancestorStr == "" {
				continue
			}
			ancestorInt, err := strconv.ParseInt(ancestorStr, 10, 64)
			if err != nil {
				panic(err)
			}
			mergedIDs = append(mergedIDs, ancestorInt)
		}
	}

	// 查询所有文档
	documents := database.ListDocumentByIds(mergedIDs)

	// 解析到Map结构中
	var tempMap = make(map[int64]*commons.CatalogResponse)
	for _, document := range documents {
		id := document.ID
		var responses []*commons.CatalogResponse
		catalogResponse := commons.CatalogResponse{
			Id:          id,
			ParentId:    document.ParentID,
			Level:       document.Level,
			Title:       document.Title,
			SubList:     responses,
			Permissions: &commons.Permissions{},
		}
		tempMap[id] = &catalogResponse
	}

	// 查询所有文档权限
	permissions := database.ListPermissionByGroupIds(groups, commons.RESOURCE_DOCUMENT)
	for _, permission := range permissions {

		if r := tempMap[permission.ResourceID]; r != nil {
			switch permission.PermissionType {
			case commons.OPERATION_ACCESS:
				r.Permissions.Access = true
			case commons.OPERATION_CREATE:
				r.Permissions.Create = true
				r.Permissions.Access = true
			case commons.OPERATION_DELETE:
				r.Permissions.Delete = true
				r.Permissions.Access = true
			case commons.OPERATION_UPDATE:
				r.Permissions.Update = true
				r.Permissions.Access = true
			case commons.OPERATION_MOVE:
				r.Permissions.Move = true
				r.Permissions.Access = true
			case commons.OPERATION_OWN:
				r.Permissions.Access = true
				r.Permissions.Update = true
				r.Permissions.Delete = true
				r.Permissions.Create = true
				r.Permissions.Move = true
				r.Permissions.Own = true
			}
		}
	}

	// 组合list
	var res []*commons.CatalogResponse
	for _, catalogResponse := range tempMap {
		parentId := catalogResponse.ParentId
		if r := tempMap[parentId]; r != nil {
			r.SubList = append(r.SubList, catalogResponse)
		} else {
			res = append(res, catalogResponse)
		}
	}

	return res
}

func EditDocument(documentParam commons.DocumentRequest) {
	document := database.Document{
		ID:      documentParam.Id,
		Title:   documentParam.Title,
		Content: documentParam.Content,
	}

	database.UpdateDocument(&document)
}

func AddDocument(documentParam commons.DocumentRequest) {
	// todo 校验parentId
	parentDocument := database.GetById(documentParam.ParentId)
	if &parentDocument == nil {
		panic(commons.CustomClientError("上级文档不存在或已被删除"))
	}

	// todo 校验是否拥有上级文档的新增权限

	document := database.Document{
		ID:        documentParam.Id,
		ParentID:  parentDocument.ID,
		Level:     parentDocument.Level + 1,
		Ancestors: parentDocument.Ancestors + string(parentDocument.ID),
		Title:     documentParam.Title,
		//Author:     commons.GetLocalSession().UserId,  TODO
		Content:    documentParam.Content,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}

	// 保存
	database.InsertDocument(document)
}

// UpdateDocument 更新文档
func UpdateDocument(documentParam commons.DocumentRequest) {
	// 文档是否存在
	var _ = database.GetById(documentParam.Id)

	// 更新
	document := database.Document{ID: documentParam.Id, Title: documentParam.Title, Content: documentParam.Content}
	database.UpdateDocument(&document)
}

// MoveDocument 移动文档
func MoveDocument(documentParam commons.DocumentRequest) {
	database.UpdateParentId(documentParam.Id, documentParam.ParentId)
}

// GetDocument 获取文档
func GetDocument(session commons.Session, id int64) (documentResponse commons.DocumentResponse) {

	document := database.GetById(int64(id))

	// 当前用户拥有此资源的权限列表
	permission, err := database.ListUserPermission(session.UserID, id, session.Groups, commons.RESOURCE_DOCUMENT)
	if err != nil {
		panic(err)
	}

	// 如果没有权限
	if (permission == nil || len(permission) == 0) && !session.IsAdmin() {
		panic(commons.UnAuthorizationErr)
	}

	//
	documentResponse = commons.DocumentResponse{
		Id:         document.ID,
		ParentId:   document.ParentID,
		Level:      document.Level,
		Ancestors:  document.Ancestors,
		Title:      document.Title,
		Author:     document.Author,
		Content:    document.Content,
		CreateTime: document.CreateTime,
		UpdateTime: document.UpdateTime,
	}
	return documentResponse
}

func DeleteDocument(id int64) {
	database.DeleteDocument(int64(id))
}
